package com.xunyji.demo03.realm.usedemo;

import com.xunyji.demo03.realm.MySimpleRealm01;
import com.xunyji.demo03.realm.MySimpleRealm02;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author AltEnter
 * @create 2019-01-21 21:50
 * @desc 更改SecurityManager默认的认证策略以及使用多个Realm
 **/
public class ChangeAuthenticateStrategy {
    @Test
    public void test01() {
//        创建Realm实例
        MySimpleRealm01 mySimpleRealm01 = new MySimpleRealm01();
        MySimpleRealm02 mySimpleRealm02 = new MySimpleRealm02();

//        创建SecurityManager实例
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
//        创建Authenticator实例
        ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
//        创建认证策略实例
        FirstSuccessfulStrategy firstSuccessfulStrategy = new FirstSuccessfulStrategy();
//        给Authenticator实例设置认证策略
        modularRealmAuthenticator.setAuthenticationStrategy(firstSuccessfulStrategy);
//        给SecurityManager实例设置Authenticator
        defaultSecurityManager.setAuthenticator(modularRealmAuthenticator);
//        给SecurityManager实例设置Realm
        Collection<Realm> realmSet = new HashSet<Realm>();
        realmSet.add(mySimpleRealm01);
        realmSet.add(mySimpleRealm02);
        defaultSecurityManager.setRealms(realmSet);

//        设置SecurityManager
        SecurityUtils.setSecurityManager(defaultSecurityManager);
//        获取Subject实例
        Subject subject = SecurityUtils.getSubject();
//        封装前端传过来的用户信息（两个token都可以通过，因为我们设置了多个realm，而SecurityManager默认只要一个Realm满足就可以啦）
        UsernamePasswordToken token = new UsernamePasswordToken("fury01", "111111");
//        UsernamePasswordToken token = new UsernamePasswordToken("fury02", "222222");
//        登录操作
        subject.login(token);
        System.out.println(String.format("认证结果：%s", subject.isAuthenticated()));
//        登出操作
        subject.logout();
        System.out.println(String.format("认证结果：%s", subject.isAuthenticated()));

    }
}

